<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" clearable class="!w-240px" />
      </el-form-item>
      <el-form-item prop="sort">
        <template #label>
          <Tooltip title="排序" message="排序数值越小越靠前" />
        </template>
        <el-input-number v-model="formData.sort" clearable />
      </el-form-item>
      <el-form-item label="开关" prop="enabled">
        <el-switch
          v-model="formData.enabled"
          active-text="开启"
          inactive-text="关闭"
          inline-prompt
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>

<!--suppress HtmlUnknownAttribute -->
<script setup lang="ts" name="CategoryForm">
import * as CategoryApi from '@/api/dine/category/CategoryApi'

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref<any>({
  id: undefined,
  name: '',
  sort: 1,
  enabled: true
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
})
const formRef = ref()

const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CategoryApi.getDetailById(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await CategoryApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await CategoryApi.updateById(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    sort: 1,
    enabled: true
  }
  formRef.value?.resetFields()
}
</script>
